package com.tyut.musicdreamer.framework.starter.web.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tyut.musicdreamer.framework.starter.web.interceptor.InternalRequestAuthInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * Web MVC 配置类
 * 使用全局统一的序列化配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final ObjectMapper objectMapper;
    private final InternalRequestAuthInterceptor internalRequestAuthInterceptor;

    public WebMvcConfig(ObjectMapper objectMapper, InternalRequestAuthInterceptor internalRequestAuthInterceptor) {
        this.objectMapper = objectMapper;
        this.internalRequestAuthInterceptor = internalRequestAuthInterceptor;
    }

    /**
     * 配置HTTP消息转换器，使用全局统一的ObjectMapper
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.forEach(converter -> {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter jsonConverter = (MappingJackson2HttpMessageConverter) converter;
                jsonConverter.setObjectMapper(objectMapper);
            }
        });
    }

    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加内部请求认证拦截器
        registry.addInterceptor(internalRequestAuthInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/error");
    }
} 